package platform

import (
	"fmt"
	"log"

	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"

	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
)

// saveCardToDatabase 保存卡片信息到本地数据库
func (c *UnifiedCardController) saveCardToDatabase(ctx *gin.Context, cardID string, userID int64, platform string, nickname string, rechargeAmount float64, cardBin string) {
	// 检查卡片是否已存在
	var existingCard models.UserCard
	if err := c.db.Where("card_id = ?", cardID).First(&existingCard).Error; err == nil {
		// 卡片已存在，更新昵称、CardBin和充值金额
		updates := map[string]interface{}{
			"nike_name": nickname,
		}

		// 如果提供了CardBin，则更新
		if cardBin != "" {
			updates["card_bin"] = cardBin
		}

		// 累加充值金额到现有的TotalTransferAmount
		// 注意：PhotonPay平台的开卡逻辑已经在postOperation.go中处理了余额扣除和卡片金额更新
		// 这里只处理HlPay平台，避免重复计算
		if rechargeAmount > 0 && platform != "photonpay" {
			// 使用字符串转换避免精度损失
			rechargeAmountStr := fmt.Sprintf("%.2f", rechargeAmount)
			rechargeAmountDecimal, err := decimal.NewFromString(rechargeAmountStr)
			if err != nil {
				log.Printf("[saveCardToDatabase] 金额转换失败: %v", err)
				rechargeAmountDecimal = decimal.NewFromFloat(rechargeAmount) // 降级处理
			}
			updates["TotalTransferAmount"] = existingCard.TotalTransferAmount.Add(rechargeAmountDecimal)
		}

		// 更新卡片信息
		if err := c.db.Model(&existingCard).Updates(updates).Error; err != nil {
			log.Printf("[saveCardToDatabase] 更新现有卡片失败: CardID=%s, 错误: %v", cardID, err)
		} else {
			// 计算总金额用于日志显示
			if rechargeAmount > 0 && platform != "photonpay" {
				rechargeAmountStr := fmt.Sprintf("%.2f", rechargeAmount)
				rechargeAmountDecimal, err := decimal.NewFromString(rechargeAmountStr)
				if err != nil {
					rechargeAmountDecimal = decimal.NewFromFloat(rechargeAmount)
				}
				log.Printf("[saveCardToDatabase] 更新现有卡片: CardID=%s, CardBin=%s, 新增充值金额=%s, 总金额=%s",
					cardID, cardBin, rechargeAmountDecimal.String(), existingCard.TotalTransferAmount.Add(rechargeAmountDecimal).String())
			} else {
				log.Printf("[saveCardToDatabase] 更新现有卡片: CardID=%s, CardBin=%s, 平台=%s (跳过余额更新)",
					cardID, cardBin, platform)
			}
		}
	} else {
		// 创建新卡片记录，使用统一状态
		// 注意：PhotonPay平台的开卡逻辑已经在postOperation.go中处理了余额扣除和卡片金额更新
		// 这里只处理HlPay平台，避免重复计算
		var totalTransferAmount decimal.Decimal
		if rechargeAmount > 0 && platform != "photonpay" {
			// 使用字符串转换避免精度损失
			rechargeAmountStr := fmt.Sprintf("%.2f", rechargeAmount)
			if amountDecimal, err := decimal.NewFromString(rechargeAmountStr); err == nil {
				totalTransferAmount = amountDecimal
			} else {
				totalTransferAmount = decimal.NewFromFloat(rechargeAmount)
			}
		} else {
			totalTransferAmount = decimal.Zero
		}

		newCard := models.UserCard{
			UserID:              userID,
			CardID:              cardID,
			Platform:            platform,
			CardStatus:          "normal", // 默认正常状态
			CardBin:             cardBin,  // 使用传入的CardBin
			NikeName:            nickname,
			TotalTransferAmount: totalTransferAmount,
			CardType:            "recharge", // 默认常规卡
		}

		if err := c.db.Create(&newCard).Error; err != nil {
			log.Printf("[saveCardToDatabase] 创建新卡片失败: CardID=%s, 错误: %v", cardID, err)
		} else {
			if rechargeAmount > 0 && platform != "photonpay" {
				log.Printf("[saveCardToDatabase] 创建新卡片: CardID=%s, CardBin=%s, 充值金额=%s, 总金额=%s",
					cardID, cardBin, newCard.TotalTransferAmount.String(), newCard.TotalTransferAmount.String())
			} else {
				log.Printf("[saveCardToDatabase] 创建新卡片: CardID=%s, CardBin=%s, 平台=%s (跳过余额更新)",
					cardID, cardBin, platform)
			}
		}
	}
}

// updateCardStatusInDatabase 更新本地数据库中的卡片状态
func (c *UnifiedCardController) updateCardStatusInDatabase(ctx *gin.Context, cardID string, status string) {
	// 验证状态是否有效
	if !common.IsValidCardStatus(status) {
		log.Printf("[updateCardStatusInDatabase] 无效的卡片状态: CardID=%s, 状态=%s", cardID, status)
		return
	}

	var userCard models.UserCard
	if err := c.db.Where("card_id = ?", cardID).First(&userCard).Error; err == nil {
		if err := c.db.Model(&userCard).Update("card_status", status).Error; err != nil {
			log.Printf("[updateCardStatusInDatabase] 更新卡片状态失败: CardID=%s, 状态=%s, 错误: %v", cardID, status, err)
		} else {
			log.Printf("[updateCardStatusInDatabase] 成功更新卡片状态: CardID=%s, 原状态=%s, 新状态=%s, 描述=%s",
				cardID, userCard.CardStatus, status, common.GetCardStatusDescription(status))
		}
	} else {
		log.Printf("[updateCardStatusInDatabase] 找不到卡片: CardID=%s, 错误: %v", cardID, err)
	}
}

// updateCardTotalTransferAmount 更新卡片的总转账金额
func (c *UnifiedCardController) updateCardTotalTransferAmount(ctx *gin.Context, cardID string, userID int64, amount decimal.Decimal) error {
	var userCard models.UserCard
	if err := c.db.Where("card_id = ? AND user_id = ?", cardID, userID).First(&userCard).Error; err != nil {
		return fmt.Errorf("找不到卡片记录: %v", err)
	}

	// 累加充值金额到现有的TotalTransferAmount
	newTotalTransferAmount := userCard.TotalTransferAmount.Add(amount)
	if err := c.db.Model(&userCard).Update("TotalTransferAmount", newTotalTransferAmount).Error; err != nil {
		return fmt.Errorf("更新卡片总转账金额失败: %v", err)
	}

	log.Printf("[updateCardTotalTransferAmount] 卡片总转账金额更新成功: CardID=%s, 原金额=%s, 新增金额=%s, 新总金额=%s",
		cardID, userCard.TotalTransferAmount.String(), amount.String(), newTotalTransferAmount.String())

	return nil
}

// saveCardToDatabaseAsync 异步保存卡片信息到数据库（用于批量开卡）
func (c *UnifiedCardController) saveCardToDatabaseAsync(cardID string, userID int64, platform string, nickname string, rechargeAmount float64, cardBin string) {
	// 检查卡片是否已存在
	var existingCard models.UserCard
	if err := c.db.Where("card_id = ?", cardID).First(&existingCard).Error; err == nil {
		// 卡片已存在，更新昵称、CardBin和充值金额
		updates := map[string]interface{}{
			"nike_name": nickname,
		}

		// 如果提供了CardBin，则更新
		if cardBin != "" {
			updates["card_bin"] = cardBin
		}

		// 累加充值金额到现有的TotalTransferAmount
		if rechargeAmount > 0 && platform != "photonpay" {
			rechargeAmountStr := fmt.Sprintf("%.2f", rechargeAmount)
			rechargeAmountDecimal, err := decimal.NewFromString(rechargeAmountStr)
			if err != nil {
				log.Printf("[saveCardToDatabaseAsync] 金额转换失败: %v", err)
				rechargeAmountDecimal = decimal.NewFromFloat(rechargeAmount)
			}
			updates["TotalTransferAmount"] = existingCard.TotalTransferAmount.Add(rechargeAmountDecimal)
		}

		// 更新卡片信息
		if err := c.db.Model(&existingCard).Updates(updates).Error; err != nil {
			log.Printf("[saveCardToDatabaseAsync] 更新现有卡片失败: CardID=%s, 错误: %v", cardID, err)
		} else {
			log.Printf("[saveCardToDatabaseAsync] 更新现有卡片: CardID=%s, CardBin=%s, 昵称=%s", cardID, cardBin, nickname)
		}
	} else {
		// 创建新卡片记录
		var totalTransferAmount decimal.Decimal
		if rechargeAmount > 0 && platform != "photonpay" {
			rechargeAmountStr := fmt.Sprintf("%.2f", rechargeAmount)
			if amountDecimal, err := decimal.NewFromString(rechargeAmountStr); err == nil {
				totalTransferAmount = amountDecimal
			} else {
				totalTransferAmount = decimal.NewFromFloat(rechargeAmount)
			}
		} else {
			totalTransferAmount = decimal.Zero
		}

		newCard := models.UserCard{
			UserID:              userID,
			CardID:              cardID,
			Platform:            platform,
			CardStatus:          "normal",
			CardBin:             cardBin,
			NikeName:            nickname,
			TotalTransferAmount: totalTransferAmount,
			CardType:            "recharge",
		}

		if err := c.db.Create(&newCard).Error; err != nil {
			log.Printf("[saveCardToDatabaseAsync] 创建新卡片失败: CardID=%s, 错误: %v", cardID, err)
		} else {
			log.Printf("[saveCardToDatabaseAsync] 创建新卡片: CardID=%s, CardBin=%s, 昵称=%s", cardID, cardBin, nickname)
		}
	}
}
